package org.tgcloud.group.service.manager.notify;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tgcloud.group.core.APPResultMessage;
import org.tgcloud.group.core.ResultMessage;
import org.tgcloud.group.entity.*;
import org.tgcloud.group.repository.*;
import org.tgcloud.group.web.controller.dto.notify.SystemNotifyDTO;
import org.tgcloud.group.web.controller.dto.notify.SystemNotifyTemplateDTO;
import org.tgcloud.group.web.controller.req.notify.notifyManageReq.NotifyIdsReq;
import org.tgcloud.group.web.controller.req.notify.notifyManageReq.NotifyManageListReq;
import org.tgcloud.group.web.websocket.WebSocketServer;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: zhy
 * @Created: 2025-09-09-下午6:49
 * @Description:
 */
@Service
public class NotifyService {

    @Autowired
    private SystemNotifyTemplateMapper notifyTemplateMapper;

    @Autowired
    private SystemNotifyMessageMapper systemNotifyMessageMapper;

    @Autowired
    private SysManagerUserMapper sysManagerUserMapper;

    @Autowired
    private MjBusinessPersonMapper businessPersonMapper;

    @Autowired
    private MjNormalUserMapper normalUserMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private MjProjectMapper projectMapper;

    @Autowired
    private ProjectUserMapper projectUserMapper;

    public String getUsernameByIdAndType(Integer userId, Short userType){
        // userType: 1、小程序用户，2、后台账户，3、商务账户
        String username = "未知";
        if (userType == 1){
            MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(userId);
            username = mjNormalUser.getNickName();
        } else if (userType == 2) {
            SysManagerUser managerUser = sysManagerUserMapper.selectByPrimaryKey(userId);
            username = managerUser.getUsername();
        } else if (userType == 3) {
            MjBusinessPerson businessPerson = businessPersonMapper.selectByPrimaryKey(userId);
            username = businessPerson.getUsername();
        }
        return username;
    }


    public void doSendNotifyByRoleId(Integer userId, Short userType, String templateCode, Map<String, Object> templateParams, Integer projectId){
        SystemNotifyTemplate systemNotifyTemplate = notifyTemplateMapper.selectMsgByCode(templateCode);
        if (systemNotifyTemplate != null){
            String roleIds = systemNotifyTemplate.getRoleId();
            String[] roleIdsList = roleIds.split(",");
            List<ProjectUser> projectUsers = projectUserMapper.selectListByProjectIdAndRoleId(roleIdsList, projectId);
            if (!projectUsers.isEmpty()){
                for (ProjectUser projectUser : projectUsers){
                    doSendNotify(projectUser.getUserId(), projectUser.getUserType(),templateCode, templateParams,  userId, userType, projectId);
                }
            }
        }
    }

    // 发送消息
    public APPResultMessage doSendNotify(Integer userId, Short userType, String templateCode, Map<String, Object> templateParams, Integer sendUserId, Short sendUserType, Integer projectId){
        SystemNotifyTemplate systemNotifyTemplate = notifyTemplateMapper.selectMsgByCode(templateCode);
        if (systemNotifyTemplate == null){
            return new APPResultMessage(7001, "该消息模板暂无数据");
        }
        if (projectId != null){
            MjProject mjProject = projectMapper.selectByPrimaryKey(projectId);
            templateParams.put("projectName", mjProject.getName());
        }
        if (templateParams != null && !templateParams.isEmpty()){
            templateParams.put("sendUsername", getUsernameByIdAndType(sendUserId, sendUserType));
            boolean checkParamsKey = false;
            String paramsKey = "";
            for (String key : templateParams.keySet()){
                Object value = templateParams.get(key);
                if (value == null) {
                    checkParamsKey = true;
                    paramsKey = String.format("模板参数(%1$s)缺失", key);
                    break;
                }
            }
            if (checkParamsKey){
                return new APPResultMessage(7002, paramsKey);
            }
        }
        // 发送站内信
        String content = StrUtil.format(systemNotifyTemplate.getContent(), templateParams);
        createNotifyMessage(userId, userType, systemNotifyTemplate, content, templateParams, sendUserId, sendUserType, projectId);
        return APPResultMessage.getSuccessMessage();
    }

    public Integer createNotifyMessage(Integer userId, Short userType,
                                    SystemNotifyTemplate template, String templateContent, Map<String, Object> templateParams, Integer sendUserId, Short sendUserType, Integer projectId) {
        SystemNotifyMessage message = new SystemNotifyMessage();
        message.setUserId(userId);
        message.setUserType(userType);
        message.setTemplateId(template.getId());
        message.setTemplateCode(template.getCode());
        message.setTemplateType(template.getType());
        message.setTemplateNickname(sendUserId != null ? getUsernameByIdAndType(sendUserId, sendUserType) : template.getNickname());
        message.setTemplateContent(templateContent);
        if (templateParams != null){
            message.setTemplateParams(JSON.toJSONString(templateParams));
        }
        message.setReadStatus(false);
        message.setProjectId(projectId);
        systemNotifyMessageMapper.insertSelective(message);
        webSocketServer.sendMsgToUserId(templateContent, userId, userType);
        return message.getId();
    }

    public APPResultMessage getNotifyList(NotifyManageListReq req, Integer userId, Short userType) {
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        List<SystemNotifyDTO> list = systemNotifyMessageMapper.selectManageList(userId, userType, req.getProjectId(), req.getReadStatus());
        PageInfo<SystemNotifyDTO> tables = new PageInfo<>(list);
        ResultMessage result = ResultMessage.builder().setList(tables.getList()).setAllPageNumber(tables.getPages()).setCount(tables.getTotal());
        APPResultMessage message = APPResultMessage.getSuccessMessage();
        message.setResult(result);
        return message;
    }

    public APPResultMessage doReadBatchNotify(NotifyIdsReq req) {
        String[] readIds = req.getReadIds().split(",");
        systemNotifyMessageMapper.updateReadStatusByIds(readIds);
        return APPResultMessage.getSuccessMessage();
    }
}
